package com.xl.basic.controller;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.StrUtil;
import com.xl.basic.annotation.LogIgnored;
import com.xl.basic.annotation.LoginIgnored;
import com.xl.basic.entity.Properties;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.result.LoginResult;
import com.xl.basic.service.LoginService;
import com.xl.basic.utils.PropUtils;
import com.xl.basic.utils.ServletUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author 钟勇
 * Create in 2024/1/18 14:09
 */
@Tag(name = "微信公众号")
@RestController
@RequestMapping("/WxMp")
@LoginIgnored
@LogIgnored
@RequiredArgsConstructor
public class WxMpController {
    private final WxMpService wxMpService;
    private final LoginService loginService;

    @Operation(summary = "获取微信JSAPI参数")
    @PostMapping(value = "/createJsapiSignature")
    public Result<WxJsapiSignature> createJsapiSignature(String url) {
        WxJsapiSignature jsapiSignature;
        try {
            jsapiSignature = wxMpService.createJsapiSignature(url);
        } catch (WxErrorException e) {
            return ResultEnums.Exception.getResult(e.getMessage());
        }

        return ResultEnums.Success.getDataResult(jsapiSignature);
    }

    @Operation(summary = "微信登录")
    @GetMapping(value = "/mpAuth")
    public void mpAuth(String back) throws IOException {
        Properties.Basic basic = PropUtils.getProp().getBasic();
        String domain = basic.getDomain();

        UrlQuery urlQuery = new UrlQuery();
        urlQuery.add("back", back);
//        urlQuery.add("back", URLEncodeUtil.encodePathSegment(back));

        String url = domain + "/WxMp/mpAuthCallback?" + urlQuery.build(Charset.defaultCharset());
        String authUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);

        HttpServletResponse response = ServletUtils.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        response.sendRedirect(authUrl);
    }

    @Operation(summary = "微信登录回调")
    @GetMapping(value = "/mpAuthCallback")
    public void mpAuthCallback(String code, String back) throws IOException {
        HttpServletResponse response = ServletUtils.getResponse();
        response.setContentType("text/html;charset=UTF-8");

        UrlQuery errorUrlQuery = new UrlQuery();
        errorUrlQuery.add("back", back);

        if (StrUtil.isBlank(code)) {
            errorUrlQuery.add("msg", "微信鉴权失败");
            String errorUrl = "/m/error.html?" + errorUrlQuery.build(Charset.defaultCharset());
            response.sendRedirect(errorUrl);
            return;
        }

        Result<LoginResult> loginRes = loginService.loginByWxCode(code);
        if (loginRes.isErr()) {
            errorUrlQuery.add("msg", loginRes.getMessage());
            String errorUrl = "/m/error.html?" + errorUrlQuery.build(Charset.defaultCharset());
            response.sendRedirect(errorUrl);
            return;
        }

        response.sendRedirect(back);
    }

}
